<template>
  <div class="p-4">
    <h1 class="text-2xl font-bold text-center mb-4">九宫格/多格切图</h1>
    <div class="bg-white rounded shadow p-4 max-w-2xl mx-auto">
      <div class="flex flex-col items-center">
        <input type="file" accept="image/*" @change="onFileChange" class="mb-4" />
        <div v-if="imageUrl" class="relative mb-4">
          <img :src="imageUrl" ref="imgRef" class="max-w-xs max-h-80 border" />
          <div v-if="showGrid" class="absolute inset-0 pointer-events-none">
            <svg :width="imgWidth" :height="imgHeight" style="position:absolute;top:0;left:0;">
              <line
                v-for="i in cols - 1"
                :key="'v'+i"
                :x1="(imgWidth/cols)*i"
                y1="0"
                :x2="(imgWidth/cols)*i"
                :y2="imgHeight"
                stroke="#fff"
                stroke-width="2"
              />
              <line
                v-for="i in rows - 1"
                :key="'h'+i"
                x1="0"
                :y1="(imgHeight/rows)*i"
                :x2="imgWidth"
                :y2="(imgHeight/rows)*i"
                stroke="#fff"
                stroke-width="2"
              />
            </svg>
          </div>
        </div>
        <div class="flex gap-2 mb-4">
          <label>切割列数：<input type="number" v-model.number="cols" min="2" max="10" class="w-16 border rounded px-1" /></label>
          <label>切割行数：<input type="number" v-model.number="rows" min="2" max="10" class="w-16 border rounded px-1" /></label>
          <label><input type="checkbox" v-model="showGrid" /> 显示分割线</label>
        </div>
        <button class="btn btn-primary" :disabled="!imageUrl" @click="splitImage">生成切图</button>
      </div>
      <div v-if="splitImages.length" class="mt-8">
        <h2 class="text-lg font-semibold mb-2">处理结果</h2>
        <div class="grid gap-2" :style="{gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`}" >
          <div v-for="(img, idx) in splitImages" :key="idx" class="border">
            <img :src="img" class="w-full" />
            <a :href="img" :download="`split_${idx+1}.png`" class="block text-center text-blue-500 text-xs py-1">下载</a>
          </div>
        </div>
        <button class="btn btn-success mt-4" @click="downloadAll">批量下载切图</button>
      </div>
      <div class="mt-8 bg-blue-50 p-3 rounded text-xs text-blue-800">
        <b>工具简介：</b><br>
        九宫格/多格切图：将图片切割为指定行列数的多张小图，常用于社交平台拼图等场景。<br>
        支持自定义行列数，支持批量下载切图结果。
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'

const imageUrl = ref('')
const splitImages = ref([])
const rows = ref(3)
const cols = ref(3)
const showGrid = ref(true)
const imgRef = ref(null)
const imgWidth = ref(0)
const imgHeight = ref(0)

function onFileChange(e) {
  const file = e.target.files[0]
  if (!file) return
  const reader = new FileReader()
  reader.onload = ev => {
    imageUrl.value = ev.target.result
    splitImages.value = []
    nextTick(() => updateImgSize())
  }
  reader.readAsDataURL(file)
}

function updateImgSize() {
  if (imgRef.value) {
    imgWidth.value = imgRef.value.naturalWidth
    imgHeight.value = imgRef.value.naturalHeight
  }
}

async function splitImage() {
  await nextTick()
  updateImgSize()
  const img = imgRef.value
  if (!img) return
  const w = img.naturalWidth
  const h = img.naturalHeight
  const cellW = Math.floor(w / cols.value)
  const cellH = Math.floor(h / rows.value)
  const canvas = document.createElement('canvas')
  canvas.width = cellW
  canvas.height = cellH
  const ctx = canvas.getContext('2d')
  const imgs = []
  for (let r = 0; r < rows.value; r++) {
    for (let c = 0; c < cols.value; c++) {
      ctx.clearRect(0, 0, cellW, cellH)
      ctx.drawImage(img, c * cellW, r * cellH, cellW, cellH, 0, 0, cellW, cellH)
      imgs.push(canvas.toDataURL('image/png'))
    }
  }
  splitImages.value = imgs
}

function downloadAll() {
  splitImages.value.forEach((img, idx) => {
    const a = document.createElement('a')
    a.href = img
    a.download = `split_${idx+1}.png`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  })
}
</script>

<style scoped>
.btn {
  @apply px-4 py-1 rounded bg-blue-500 text-white hover:bg-blue-600 transition;
}
.btn-success {
  @apply bg-green-500 hover:bg-green-600;
}
</style>
